<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="手机号" prop="userPhone">
        <el-input v-model="queryParams.userPhone" placeholder="请输入手机号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="用户姓名" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入用户姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="身份证号" prop="userIdcard">
        <el-input v-model="queryParams.userIdcard" placeholder="请输入用户身份证号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="用户性别" prop="userSex">
        <el-select v-model="queryParams.userSex" placeholder="请选择用户性别" clearable>
          <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="用户状态" prop="userState">
        <el-select v-model="queryParams.userState" placeholder="请选择用户状态" clearable>
          <el-option v-for="dict in dict.type.userstart" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['tuser:tuser:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['tuser:tuser:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['tuser:tuser:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['tuser:tuser:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" @click="handlemessage">批量发送消息</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tuserList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="30" align="center" />
      <el-table-column label="用户ID" align="center" prop="userId" width="80" />
      <el-table-column label="手机号" align="center" prop="userPhone" width="200" />
      <!-- <el-table-column label="用户密码" align="center" prop="userPassword" /> -->
      <el-table-column label="用户姓名" align="center" prop="userName" width="100" />
      <el-table-column label="身份证号" align="center" prop="userIdcard" width="200" />
      <el-table-column label="出生日期" align="center" prop="userBirthday" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.userBirthday, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户性别" align="center" prop="userSex" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.userSex" />
        </template>
      </el-table-column>
      <el-table-column label="用户状态" align="center" prop="userState" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.userstart" :value="scope.row.userState" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['tuser:tuser:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="go(scope.row)"
            v-hasPermi="['tuser:tuser:updateInfo']">启用禁用</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleResetPwd(scope.row)"
            v-hasPermi="['tuser:tuser:update']">重置密码</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['tuser:tuser:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :role="rules">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="手机号" prop="userPhone">
          <el-input v-model="form.userPhone" placeholder="请输入手机号" />
        </el-form-item>
        <!-- 修改时不显示密码 -->
        <el-form-item v-if="!isEdit" label="用户密码" prop="userPassword">
          <el-input v-model="form.userPassword" placeholder="请输入用户密码" />
        </el-form-item>
        <el-form-item label="用户姓名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户姓名" />
        </el-form-item>
        <el-form-item label="身份证号" prop="userIdcard">
          <el-input v-model="form.userIdcard" placeholder="请输入用户身份证号" />
        </el-form-item>
        <el-form-item label="出生日期" prop="userBirthday">
          <el-date-picker clearable v-model="form.userBirthday" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择用户出生日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="用户性别" prop="userSex">
          <el-select v-model="form.userSex" placeholder="请选择用户性别">
            <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="用户状态" prop="userState">
          <el-select v-model="form.userState" placeholder="请选择用户状态">
            <el-option v-for="dict in dict.type.string" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 提交禁用理由 -->
    <el-dialog :title="'启用禁用理由'" :visible.sync="hidden" width="600px" top="50%" append-to-body>
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item label="启用禁用理由">
          <el-input type="textarea" v-model="form.desc" placeholder="启用禁用理由"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="confirmDisable">提交启用禁用理由</el-button>
          <el-button @click="hidden = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 批量发送消息对话框 -->
    <el-dialog title="批量发送消息" :visible.sync="openDialog" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="消息内容" prop="messageContent">
          <el-input v-model="form.messageContent" type="textarea" :rows="4" placeholder="请输入消息内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmSend">确 定</el-button>
        <el-button @click="openDialog = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTuser, getTuser, delTuser, addTuser, updateTuser, resetUserPwd, addMessage,updateUserInfo} from "@/api/tuser/tuser";
import { insertBatchMessages } from "@/api/message/message";
export default {
  name: "Tuser",
  dicts: ['sys_user_sex', 'userstart'],
  data() {
    return {
      //消息发送
      openDialog: false,
      isEdit: false,
      hidden: false,
      //发送禁用的理由
      textarea: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      tuserList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userPhone: null,
        userName: null,
        userIdcard: null,
        userSex: null,
        userState: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userPhone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^(?:(?:\+|00)86)?1\d{10}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        userPassword: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码不能少于6位', trigger: 'blur' },
          {
            pattern: /^(?=.*\d)(?=.*[A-Z])(?=.*[a-z]).{6,}$/,
            message: '密码必须包含数字、大写字母和小写字母',
            trigger: 'blur'
          },
          {
            pattern: /^[^<>"'|\\]+$/,
            message: '密码不能包含非法字符：< > " \' \\ |',
            trigger: 'blur'
          }
        ],
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { pattern: /^[^<>"'|\\]+$/, message: "用户名不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }
        ],
        userIdcard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          {
            pattern: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/,
            message: '请输入正确的身份证号', trigger: 'blur'
          }
        ],
        userBirthday: [
          { required: true, message: '请选择出生日期', trigger: 'change' }
        ],
        userSex: [
          { required: true, message: '请选择用户性别', trigger: 'change' }
        ],
        userState: [
          { required: true, message: '请选择用户状态', trigger: 'change' }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listTuser(this.queryParams).then(response => {
        this.tuserList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: null,
        userPhone: null,
        userPassword: null,
        userName: null,
        userIdcard: null,
        userBirthday: null,
        userSex: null,
        userState: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 启用禁用操作 */
    go(row) {
      this.form.userId = row.userId;
      this.hidden = true;
    },

    /** 确认禁用启用操作 */
    confirmDisable() {
      // 检查禁用理由是否填写
      if (!this.form.desc) {
        this.$message.warning("请填写禁用理由");
        return;
      }

      // 先执行禁用启用操作后发送消息
      updateUserInfo(this.form.userId).then(() => {
        this.$message.success("操作成功");
        const messageData = {
          userId: this.form.userId,
          messageContent: `启用/禁用理由: ${this.form.desc || '无'}`
        };
        addMessage(messageData).then(() => {
          this.$message.success("理由已发送");
        }).catch(error => {
          this.$message.error("发送启用禁用理由失败");
        });

        this.hidden = false;
        this.form.desc = '';
        this.getList();
      }).catch(error => {
        this.$message.error("启用禁用操作失败");
      });
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 批量发送操作 */
    handlemessage() {
      this.openDialog = true
    },
    confirmSend() {
      if (!this.form.messageContent || this.ids.length === 0) {
        this.$message.error("请填写消息内容并选择用户");
        return;
      }
      const payload = this.ids.map(userId => ({
        userId: userId,
        messageContent: this.form.messageContent
      }));
      console.log(payload);
      insertBatchMessages(payload).then(response => {
        this.$message.success("消息发送成功");
        this.openDialog = false;  
        this.getList();  
      }).catch(error => {
        this.$message.error("消息发送失败，请重试");
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.isEdit = false;
      this.reset();
      this.open = true;
      this.title = "添加用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.isEdit = true;
      this.reset();
      const userId = row.userId || this.ids

      getTuser(userId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用户";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const action = this.form.userId ? updateTuser : addTuser;
          const successMessage = this.form.userId ? "修改成功" : "新增成功";

          action(this.form)
            .then(response => {
              this.$modal.msgSuccess(successMessage);
              this.open = false;
              this.getList();
            })
            .catch(error => {
              console.error(successMessage + "失败:", error);
              this.$modal.msgError(successMessage + "失败");
            });
        } else {
          this.$modal.msgError("请检查输入的内容是否有误");
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function () {
        return delTuser(userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    // 重置密码
    handleResetPwd(row) {
      const userIds = row.userId || this.ids;
      this.$modal.confirm('是否确认重置用户ID为"' + userIds + '"的密码为123456？')
        .then(() => {
          return resetUserPwd(userIds);
        })
        .then(() => {
          this.getList();  // 刷新用户列表
          this.$modal.msgSuccess("密码重置成功");
          // 发送消息
          const messageData = {
            userId: userIds,
            messageContent: '您的密码已被管理员重置为123456，请及时更改密码。',
          };
          return addMessage(messageData);
        })
        .catch(error => {
          this.$modal.msgError("密码重置失败");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('tuser/tuser/export', {
        ...this.queryParams
      }, `tuser_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
